class Solution(object):
    def nearestValidPoint(self, x, y, points):
        min_dist = float('inf')
        out_index = -1
        for index, (ux, uy) in enumerate(points):
            if ux == x or uy == y:
                dist = abs(ux - x) + abs(uy - y)
                if dist < min_dist:
                    out_index = index
                    min_dist = dist
                else:
                    if dist == min_dist:
                        out_index = min(out_index, index)
        return out_index